import { message } from '@/components/basic/message';
import * as XLSX from 'xlsx';

type XlsxRow = {
  key: string;
  value: () => any;
  index: number;
};

type XlsxCol = XlsxRow;

type XlsxOptions = {
  DomId: string;
  Arows?: XlsxRow[];
  Drows?: XlsxRow[];
  Acols?: XlsxCol[];
  Dcols?: XlsxCol[];
};

export const useXlsx = (id: string) => {
  class XlsxHandler {
    private DomId: string;
    private xlsxOption: Omit<XlsxOptions, 'DomId'>;

    constructor(option: string | XlsxOptions, config: Omit<XlsxOptions, 'DomId'> = {}) {
      this.DomId = typeof option === 'string' ? option : option.DomId;
      this.xlsxOption = typeof option === 'string' ? config : option;
    }

    addRows(rows: XlsxRow[]) {
      if (!this.xlsxOption.Arows) {
        this.xlsxOption.Arows = rows;
      } else this.xlsxOption.Arows = this.xlsxOption.Arows.concat(rows);
    }

    addCols(cols: XlsxCol[]) {
      this.xlsxOption.Acols = cols;
    }

    deleteRows(rows: XlsxRow[]) {
      this.xlsxOption.Drows = rows;
    }

    deleteCols(cols: XlsxCol[]) {
      this.xlsxOption.Dcols = cols;
    }

    exportTableAsXlsx() {
      return exportTableAsXlsx(this.DomId, this.xlsxOption);
    }
  }

  return new XlsxHandler(id || 'my-table');
};

export const exportTableAsXlsx = (option: string | XlsxOptions, config: Omit<XlsxOptions, 'DomId'> = {}) => {
  const DomId = typeof option === 'string' ? option : option.DomId;
  const xlsxOption = typeof option === 'string' ? config : option;

  var table_elt = document.getElementById(DomId);

  if (!table_elt) {
    message.error('未找到id为' + DomId + '的元素');
  }

  // 提取数据（从表中创建工作簿对象）
  var workbook = XLSX.utils.table_to_book(table_elt);

  // 添加新行
  const addRows = (rows: XlsxRow[]) => {
    // var  ws  =  workbook . Sheets [ "Sheet1" ] ; // 获取工作表
    // XLSX . utils . sheet_add_aoa ( ws ,  [ [ "Created " + new  Date ( ) . toISOString ( ) ] ] ,  { origin : - 1 } ) ;

    rows.forEach(row => {
      var ws = workbook.Sheets[row.key || 'Sheet1']; // 获取工作表
      XLSX.utils.sheet_add_aoa(ws, [[row.value()]], { origin: row.index || -1 });
    });
  };

  if (xlsxOption.Arows) {
    addRows(xlsxOption.Arows); // 添加新行
  }

  // 打包并发布数据（`writeFile` 尝试写入并保存 XLSX 文件）
  const exportFile = () => XLSX.writeFile(workbook, 'Report.xlsx');

  return {
    exportFile
  };
};
